//for electron
const { ipcRenderer, desktopCapturer } = require('electron');

ipcRenderer.setMaxListeners(0);

Halo.Config.bDebug = true;

var halo_i18n;
switch (ipcRenderer.sendSync('language')) {
    case 'EN':
        halo_i18n = halo_lang.EN;
        break;
    case 'CN':
        halo_i18n = halo_lang.CN;
    default:
        break;
}
var project = ipcRenderer.sendSync('project');
var version = JSON.parse(ipcRenderer.sendSync('read_file', project + 'version.json'));

var desktopLoader = function (path, name, callback) {
    var url = Halo.ResourceManager.getUrl(path, name);
    var ver = version[path] ? version[path][name] : null;
    var size = ver ? ver.size : 0;

    var type = (path === 'cfg' || path === 'js' || path === '') ? 'read_file' : 'read_binary';
    var data = ipcRenderer.sendSync(type, url);

    if (data !== "" && type === 'read_binary') {
        if (path === 'aud') {
            data = Halo.base64ToArrayBuffer(data);
        } else if (path === 'img') {
            data = 'data:img/' + name.split('.').pop().toLowerCase() + ';base64,' + data;
        } else if (path === 'vid') {
            data = 'data:video/' + name.split('.').pop().toLowerCase() + ';base64,' + data;
        } else if (Halo.ResourceManager.path3d().indexOf(path) >= 0) {
            data = Halo.base64ToUint8Array(data);
        }
    }

    if (path === 'js' && Halo.Config.bDebug) {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = url;
        script.id = name;
        script.onload = function () {
            document.head.removeChild(script);
            callback && callback(script);
            Halo.onLoadData && Halo.onLoadData(path, name, size);
        }
        document.head.appendChild(script);
    } else {
        callback && callback(data);
        Halo.onLoadData && Halo.onLoadData(path, name, size);
    }
};

var initProject = function (callback) {
    function addFiles(path, files) {
        for (let i = 0; i !== files.length; ++i) {
            var name = files[i];
            if (name.startsWith('.', 0)) {
                continue;
            }
            if (Halo.ResourceManager.path3d().indexOf(path) >= 0) {
                var suffix = name.split('.').pop();
                name = name.substring(0, name.length - suffix.length - 1);
            }
            if (path === 'img') {
                var textures = Halo.Config.get().textures;
                var texture = textures[name];
                if (texture === undefined) {
                    textures[name] = {
                        type: 'image' //video, image, altas, sprite
                    };
                }
            }

            Halo.ResourceManager.addResource(path, name);
        }
    }

    Halo.ResourceManager.clearCache();

    Halo.init(null, project, desktopLoader, function (res) {
        if (res === null) {
            var preloads = [];

            var jsfiles = JSON.parse(ipcRenderer.sendSync('list-files', 'js'));
            for (let i = 0; i !== jsfiles.length; ++i) {
                var name = jsfiles[i];
                if (name.startsWith('.', 0)) {
                    continue;
                }
                preloads.push({ path: 'js', name: name })
            }

            var audfiles = JSON.parse(ipcRenderer.sendSync('list-files', 'aud'));
            for (let i = 0; i !== audfiles.length; ++i) {
                var name = audfiles[i];
                if (name.startsWith('.', 0)) {
                    continue;
                }
                preloads.push({ path: 'aud', name: name })
            }

            var textures = Halo.Config.get().textures;
            for (var key in textures) {
                var texture = textures[key];
                var url_img = Halo.ResourceManager.getUrl('img', key);
                if (texture.type === 'sprite' || texture.type === 'atlas') {
                    var url_json = Halo.ResourceManager.getUrl('cfg', texture.json);
                    if (ipcRenderer.sendSync('exists', url_json) === 'true') {
                        preloads.push({ path: 'cfg', name: texture.json });
                    }
                    if (ipcRenderer.sendSync('exists', url_img) === 'true') {
                        preloads.push({ path: 'img', name: key });
                    }
                } else {
                    if (ipcRenderer.sendSync('exists', url_img) === 'false') {
                        delete textures[key];
                    }
                }
            }

            var vids = JSON.parse(ipcRenderer.sendSync('list-files', 'vid'));
            for (let i = 0; i !== vids.length; ++i) {
                var name = vids[i];
                if (name.startsWith('.', 0)) {
                    continue;
                }
                preloads.push({ path: 'vid', name: name })
            }

            if (preloads.length > 0) {
                Halo.ResourceManager.loadList(preloads, function (res) {
                    if (res === null) {
                        onload();
                    }
                });
            } else {
                onload();
            }

            function onload() {
                addFiles('cfg', JSON.parse(ipcRenderer.sendSync('list-files', 'cfg')));
                addFiles('geo', JSON.parse(ipcRenderer.sendSync('list-files', 'geo')));
                addFiles('ani', JSON.parse(ipcRenderer.sendSync('list-files', 'ani')));
                addFiles('mat', JSON.parse(ipcRenderer.sendSync('list-files', 'mat')));
                addFiles('mdl', JSON.parse(ipcRenderer.sendSync('list-files', 'mdl')));
                addFiles('scn', JSON.parse(ipcRenderer.sendSync('list-files', 'scn')));
                addFiles('img', JSON.parse(ipcRenderer.sendSync('list-files', 'img')));

                var config = Halo.Config.get();
                var entry_scene = config.entry_scene || 'main';
                var url = Halo.ResourceManager.getUrl('scn', entry_scene);

                if (ipcRenderer.sendSync('exists', url) === 'false') {
                    var scene = new Halo.HaloScene();
                    scene.name = entry_scene;
                    Editor.save('scn', entry_scene, scene);
                }

                config.entry_scene = entry_scene;
                Editor.save('', 'config.json', config);

                callback && callback(true);
            }
        }
    });
};